<?php 
/* 
 * This file is part of TCDB. 
 * 
 * Copyright (C) 2000-2009 
 * Technology Consultant Corps 
 * Grinnell College 
 * Grinnell, IA, 50112 
 * tc@grinnell.edu 
 * 
 * TCDB is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * TCDB is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with TCDB. If not, see <http://www.gnu.org/licenses/>. 
 * 
 
 ============================================================================= 
 
 * update_info.php -- Lets a user update his or her information in the DB,
 *                    including birthday, contact info, and dietary info.
 *		      It also handles changes in this data, if a user has
 *                    submitted changes to be made
 *		      It DOES NOT let users change information about their
 *                    username, first, and last names; a lot depends on info
 *		      like this, and the privilege could be abused
 * 
 * Author: Dylan J. Sather
 * Created: 2009-07-05 
 * Last edited: 2009-07-16
 *
 * Thanks to Andrew Kensler, James Michael-Hill, and CM Lubinski for their
 * work on update_info.php since January, 2000
 */ 
 
$page_title = "update_info.php"; 
$jquery_validate = TRUE;

require('init.php'); 
require('require_login.php'); 

/* There are three types of form data -- basic, other, and password; 
   therefore, we have to see which data the user is changing, since they 
   are stored in two different tables; this is accomplished by including 
   a hidden 'action' field that determines which action we're performing */

if (isset($_POST['action'])) {

    // We need to do some magic to make sure $receive_sub_emails and $publish_schedule are properly set
    $currently_here = (isset($_POST['currently_here'])) ? $_POST['currently_here'] : FALSE;
    $receive_sub_emails = (isset($_POST['receive_sub_emails'])) ? $_POST['receive_sub_emails'] : FALSE;
    $publish_schedule = (isset($_POST['publish_schedule'])) ? $_POST['publish_schedule'] : FALSE;

    /* We have to send the value "1" for TRUE to the MySQL DB, since it doesn't 
       read PHP's "trueness" as TRUE; send 0 for FALSE */
    if ($currently_here)
	$currently_here = 1;
    else
	$currently_here = 0;
    if ($receive_sub_emails)
	$receive_sub_emails = 1;
    else
	$receive_sub_emails = 0;
    if ($publish_schedule)
	$publish_schedule = 1;
    else
	$publish_schedule = 0;

    switch ($_POST['action']) {
	case "basic":
	    $query = sprintf("UPDATE users
			      SET email = '%s',
				  campus_phone = '%s',
				  cell_phone = '%s',
				  box_num = '%s',
				  major = '%s',
				  concentration = '%s',
				  pcard_id = '%s',
				  currently_here = '%s',
				  receive_sub_emails = '%s',
				  publish_schedule = '%s'
			      WHERE id = '%s'",
			  mysqli_real_escape_string($mysqli, $_POST['email']),
			  mysqli_real_escape_string($mysqli, $_POST['campus_phone']),
			  mysqli_real_escape_string($mysqli, $_POST['cell_phone']),
			  mysqli_real_escape_string($mysqli, $_POST['box_num']),
			  mysqli_real_escape_string($mysqli, $_POST['major']),
			  mysqli_real_escape_string($mysqli, $_POST['concentration']),
			  mysqli_real_escape_string($mysqli, $_POST['pcard_id']),
			  mysqli_real_escape_string($mysqli, $currently_here),
			  mysqli_real_escape_string($mysqli, $receive_sub_emails),
			  mysqli_real_escape_string($mysqli, $publish_schedule),
			  mysqli_real_escape_string($mysqli, $_SESSION['user_id']));

	    if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT)) {
		$message = "Basic Info Updated";
	    }
	    else {
		$message = "Your Basic Information failed to update; please contact a TCC";
	    }

	    break;
	case "other":

	    // First, get the canEat and isA input
	    $canEat = "";
	    $isA = "";

	    if ($result = $mysqli->query("SELECT symbol, type FROM dietary", MYSQLI_STORE_RESULT)) {
		while (list($symbol, $type) = $result->fetch_row()) {
		    if (isset($_POST[$type. $symbol]) && $_POST[$type . $symbol] == $symbol) {
			$$type .= $symbol;
		    }
		}
	    }
	    else {
		$message = "Failed to fetch dietary information\n";
	    }

	    /* Then, enter this info into the DB using REPLACE INTO -- if the field exists,
	       REPLACE INTO updates the field; otherwise, it creates a new field with the info */
	    $query = sprintf("REPLACE INTO users_data
			      (user_id, birthday, shirtsize, canEat, isA, 
			       fav_sweet, fav_color, fav_food, fav_drink)
			      VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')",
			  mysqli_real_escape_string($mysqli, $_SESSION['user_id']),
			  mysqli_real_escape_string($mysqli, $_POST['b_day_y'] . "-" . $_POST['b_day_m'] . "-" . $_POST['b_day_d']),
			  mysqli_real_escape_string($mysqli, $_POST['shirtsize']),
			  mysqli_real_escape_string($mysqli, $canEat),
			  mysqli_real_escape_string($mysqli, $isA),
			  mysqli_real_escape_string($mysqli, $_POST['fav_sweet']),
			  mysqli_real_escape_string($mysqli, $_POST['fav_color']),
			  mysqli_real_escape_string($mysqli, $_POST['fav_food']),
			  mysqli_real_escape_string($mysqli, $_POST['fav_drink']));

	    if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT)) {
		$message = "Other Info Updated";
	    }
	    else {
		$message .= "Your Other Information failed to update; please contact a TCC";
	    }

	    break;
	case "password":

	    // First, make sure that both passwords are not empty
	    if (!empty($_POST['password1']) && !empty($_POST['password2'])) {
		// Then make sure the password match
		if ($_POST['password1'] == $_POST['password2']) {
		    // Then update in the DB
		    $query = sprintf("UPDATE users
				      SET password = sha1('%s')
				      WHERE id = '%s'",
				  mysqli_real_escape_string($mysqli, $_POST['password1']),
				  mysqli_real_escape_string($mysqli, $_SESSION['user_id']));

		    if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT)) {
			$message = "Password successfully changed";

			// Also update $_SESSION array
			$query = sprintf("SELECT password
					  FROM users
					  WHERE id = '%s'",
				      mysqli_real_escape_string($mysqli, $_SESSION['user_id']));

			$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

			list($user_password) = $result->fetch_row();

			$result->free();

			// Make sure the password isn't empty
			if (!empty($user_password)) {
			    $_SESSION['user_password'] = $user_password;
			}
		    }
		    else
			$message = "Your password matched but failed to update; please contact a TCC";

		}
		else
		    $message = "Your passwords didn't match; please try again";
	    
	    }
	    else
		$message = "You didn't enter your new password twice; please try again";

	    break;
    }

    // If we're changing anything, we need to update the last_edited time and change the new_user field
    $last_updated = date('Y-m-d');
    $_SESSION['new_user'] = 0;

    $query = "UPDATE users
	      SET last_updated = '$last_updated',
		  new_user = '" . $_SESSION['new_user'] . "'
	      WHERE id = '" . $_SESSION['user_id'] . "'";

    $result = $mysqli->query($query, MYSQLI_STORE_RESULT);
}

// Now we need to fetch the user data, whether or not it was just changed in the DB

// Pull user info from the users and users_data in the DB
$query = sprintf("SELECT email, campus_phone, cell_phone, box_num, pcard_id, currently_here,
			 receive_sub_emails, publish_schedule, major, concentration, last_updated,
			 shirtsize, canEat, isA, fav_sweet, fav_color, fav_food, fav_drink,
			 DATE_FORMAT(birthday, '%%Y'),
			 DATE_FORMAT(birthday, '%%m'),
			 DATE_FORMAT(birthday, '%%d')
		  FROM users LEFT JOIN users_data
		  ON users.id = users_data.user_id
		  WHERE users.id = '%s'",
	      mysqli_real_escape_string($mysqli, $_SESSION['user_id']));

$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

list($email, $campus_phone, $cell_phone, $box_num, $pcard_id, $currently_here,
     $receive_sub_emails, $publish_schedule, $major, $concentration, $last_updated,
     $shirtsize, $canEat, $isA, $fav_sweet, $fav_color, $fav_food,
     $fav_drink, $b_day_y, $b_day_m, $b_day_d) = $result->fetch_row();

$result->free();

include('header.php');

// Set up initial checked status of checkbox variables
$currently_here = ($currently_here) ? "checked='checked'" : "";
$receive_sub_emails = ($receive_sub_emails) ? "checked='checked'" : "";
$publish_schedule = ($publish_schedule) ? "checked='checked'" : "";

// Print info
echo "  <div class='content_box'> <!-- CONTENT div -->";

// If we have a message, display it
if (!empty($message)) {
    echo "<p class='message'>$message</p>\n";
}

// If we have a new user, let her know why she's being redirected to the page with a quick message
if ($_SESSION['new_user']) {
    echo "<h3>Please check to make sure your information is correct<br />
	      AND enter any additional information, as requested</h3>";
}

echo "    <h2 class='underline'>Update Info</h2>
    <div class='left_content'> <!-- LEFT CONTENT div -->
      <h3 class='underline'>Basic Info</h3>
      <form id='basic_form' method='post' action='update_info.php'>
	<div> <!-- FORM div -->
	  <label for='email'>E-mail</label>
	  <input class='big_margins required' type='text' name='email' id='email' value='$email' /><br />
	  <label for='campus_phone'>Campus Phone</label>
	  <input class='big_margins' type='text' name='campus_phone' id='campus_phone' value='$campus_phone' /><br />";

// If the user doesn't have a cell phone set, ask them if she has one
if (!$cell_phone) {
    echo '<p class="bold">
	    Do you have a cell phone?
	    <span> Yes <input type="radio" name="cell" value="yes" onclick="showCellPhone();" /></span>
	    <span> No <input type="radio" name="cell" value="no" checked="checked" onclick="hideCellPhone();" /></span>
	  </p>
	  <p id="cell_phone_check">';
}

echo "	  <label for='cell_phone'>Cell Phone</label>
	  <input class='big_margins' type='text' name='cell_phone' id='cell_phone' value='$cell_phone' /><br />";

if (!$cell_phone)
    echo "	  </p>";

echo "	  <label for='box_num'>Box Number</label>
	  <input class='big_margins' type='text' name='box_num' id='box_num' value='$box_num' /><br />
	  <label for='major'>Major</label>
	  <input class='big_margins' type='text' name='major' id='major' value='$major' /><br />
	  <label for='concentration'>Concentration</label>
	  <input class='big_margins' type='text' name='concentration' id='concentration' value='$concentration' /><br />
	  <label for='pcard_id'>P-Card ID</label>
	  <input class='big_margins' type='text' name='pcard_id' id='pcard_id' value='$pcard_id' /><br />
	  <label for='currently_here'>Currently Here?</label>
	  <input class='big_margins' type='checkbox' name='currently_here' id='currently_here' $currently_here /><br />
	  <label for='receive_sub_emails'>Receive Sub Request E-mails?</label>
	  <input class='big_margins' type='checkbox' name='receive_sub_emails' id='receive_sub_emails' $receive_sub_emails /><br />
	  <label for='publish_schedule'>Publish Schedule?</label>
	  <input class='big_margins' type='checkbox' name='publish_schedule' id='publish_schedule' $publish_schedule /><br />
	  <input type='hidden' name='action' value='basic' />
	  <input class='big_margins' type='submit' value='Update Basic Info' /><br />
	</div> <!-- End FORM div -->
      </form>

      <h3 class='underline'>Other Info</h3>
      <form method='post' action='update_info.php'>
	<div> <!-- FORM div -->\n";

// Print Birthday options
$months = array ("Month", "January", "February", "March", "April",
		 "May", "June", "July", "August", "September",
		 "October", "November", "December");
	
echo "	  <label for='b_day_m'>Birthday</label>
	  <select name='b_day_m' id='b_day_m'>\n";

for ($i = 0; $i <= 12; $i++) {
    if ((!$b_day_m && $i == 0) || $b_day_m == $i) {
	echo "	    <option selected='selected' value='$i'>" . $months[$i] . "</option>\n";
    }
    else {
	echo "	    <option value='$i'>" . $months[$i] . "</option>\n";
    }
}
	    
echo "	  </select>\n
	  <select name='b_day_d'>\n";

if (!$b_day_d || $b_day_d == 0) {
    echo "	    <option selected='selected' value='0'>Day</option>\n";
}
else {
    echo "	    <option selected='selected' value='0'>Day</option>\n";
}

for ($i = 1; $i <= 31; $i++) {
    if ($b_day_d == $i) {
	echo "	    <option selected='selected' value='$i'>$i</option>\n";
    }
    else {
	echo "	    <option value='$i'>$i</option>\n";
    }
}

echo "	  </select>\n
	  <select name='b_day_y'>
	    <option selected='selected' value='0'>Year</option>\n";

$date_array = getdate();

for ($i = -15; $i >= -50; $i--) {
    $temp_year = ($date_array["year"] + $i);
    if ($b_day_y == $temp_year) {
	echo "	    <option selected='selected' value='$temp_year'>$temp_year</option>\n";
    }
    else {
	echo "	    <option value='$temp_year'>$temp_year</option>\n";
    }
}

echo "	  </select><br />\n
	  <label for='shirtsize'>T-Shirt size (S,M,L,XL,XXL)</label>
	  <input class='big_margins' type='text' name='shirtsize' id='shirtsize' size='3' value='$shirtsize' /><br />
	  <label class='bold underline'>Do you eat... ?</label><br />\n";

/* Grab Dietary Info from DB
   There is a description and symbol pair for each food; for instance,
   if the description is "Beef", the symbol is "B". We want to pull these
   pairs from the DB and display a checkbox for each with the proper
   description and symbol. Thanks to CM Lubinski for this one -- it's 
   really quite elegant */

$query = "SELECT description, symbol
	  FROM dietary
	  WHERE type='canEat'";

$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

while (list($description, $symbol) = $result->fetch_row()) {
    if (strpos($canEat, $symbol) !== false) {
	echo "	  <input type='checkbox' name='canEat" . $symbol .
		  "' value='" . $symbol . "' checked='checked' /> " . $description . "<br />\n";
    }
    else {
	echo "	  <input type='checkbox' name='canEat" . $symbol .
		  "' value='" . $symbol . "' /> " . $description . "<br />\n";
    }
}	

$result->free();

// We're doing the same as above, just for Veggy/Vegan info
echo "	  <br />\n
	  <label class='bold underline'>Are you a... ?</label><br />\n";

$query = "SELECT description,symbol
	  FROM dietary
	  WHERE type='isA'";
	
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

while (list($description, $symbol) = $result->fetch_row()) {
    if (strpos($isA, $symbol) !== false) {
	echo "	  <input type='checkbox' name='isA" . $symbol .
		  "' value='" . $symbol . "' checked='checked' /> " . $description . "<br />\n";
    }
    else {
	echo "	  <input type='checkbox' name='isA" . $symbol .
		  "' value='" . $symbol . "' /> " . $description . "<br />\n";
    }
}	

$result->free();

// Print the rest of the other info
echo "	  <br />\n
	  <label for='fav_sweet'>Favorite sweet/candy</label>
	  <input class='big_margins' type='text' name='fav_sweet' id='fav_sweet' value='$fav_sweet' /><br />
	  <label for='fav_food'>Favorite food/flavor</label>
	  <input class='big_margins' type='text' name='fav_food' id='fav_food' value='$fav_food' /><br />
	  <label for='fav_drink'>Favorite drink</label>
	  <input class='big_margins' type='text' name='fav_drink' id='fav_drink' value='$fav_drink' /><br />
	  <label for='fav_color'>Favorite color</label>
	  <input class='big_margins' type='text' name='fav_color' id='fav_color' value='$fav_color' /><br />
	  <input type='hidden' name='action' value='other' />
	  <input class='big_margins' type='submit' value='Update Other Info' /><br />
	</div> <!-- End FORM div -->
      </form>

      <h3 class='underline'>Change Password</h3>
      <form method='post' action='update_info.php'>
	<div> <!-- FORM div -->
	  <label for='password1'>New Password</label>
	  <input class='big_margins' type='password' name='password1' id='password1' /><br />
	  <label for='password2'>Repeat</label>
	  <input class='big_margins' type='password' name='password2' id='password2' /><br />
	  <input type='hidden' name='action' value='password' />
	  <input class='big_margins' type='submit' value='Change' />
	</div> <!-- End FORM div -->
      </form>
    </div> <!-- End LEFT CONTENT div -->
    <div class='right_content'> <!-- RIGHT CONTENT div -->
      <h3 class='underline'>Current Picture</h3>";

// Fetch image
$query = "SELECT user_id
	  FROM images
	  WHERE user_id='" . $_SESSION['user_id'] . "'";

$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

// If we get a result, show image; otherwise, display an error
if ($result->num_rows != 0) {
    echo "<a href='edit_photo.php'><img src='display_image.php?id=" . $_SESSION['user_id'] . "&amp;buffer=0'
					alt='Image of " . $_SESSION['username'] . "' class='no_border' /></a>\n";
}
else {
    echo "<h3>IMAGE UNAVAILABLE</h3>";
}

$result->free();

    echo"      <p id='last_updated_footer'>Info Last Updated: $last_updated</p>    
    </div> <!-- End RIGHT CONTENT div -->
  </div> <!-- End CONTENT div -->\n";

include('footer.php'); 

?> 
